package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class supplyAddHandler implements MsgHandler {
    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        TaskViewModel taskViewModel = new TaskViewModel();
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        taskViewModel.setCreateType(0);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setDesc("自动补货工单");
        List<TaskDetailsViewModel> details = new ArrayList<>();
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();
        for (SupplyChannel supplyDatum : supplyData) {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(supplyDatum.getChannelId());
            taskDetailsViewModel.setExpectCapacity(supplyDatum.getCapacity());
            taskDetailsViewModel.setSkuId(supplyDatum.getSkuId());
            String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            Long regionId = vmInfo.getRegionId();
            String roleCode = VMSystem.USER_OPERATOR;
            String key = "taskNumSet."+date+regionId+roleCode;
            Set range = redisTemplate.opsForZSet().range(key, 0, 1);
            List collect = (List) range.stream().collect(Collectors.toList());
            Integer userId = (Integer) collect.get(0);
            taskViewModel.setUserId(userId);
            details.add(taskDetailsViewModel);
        }
        taskViewModel.setDetails(details);
        taskService.createTask(taskViewModel);
    }
}
